package chat7me_1223.client.util;
import java.io.*;
public class IOUtil {
    public static String readString(InputStream in) {//用定的输入流读取字符串
        try {
            int ch1 = in.read();
            int ch2 = in.read();
            if ((ch1 | ch2) < 0)
                throw new EOFException();
            int len = (ch1 << 8) + ch2;
            byte[] data = new byte[len];
            in.read(data);
            return new String(data, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeShort(short s, OutputStream out) {//写出short整数
        try {
            DataOutputStream dos = new DataOutputStream(out);
            dos.writeShort(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeString(String str, OutputStream out) {//写出一个字符串
        try {
            byte[] data = str.getBytes("utf-8");
            writeShort((short) data.length, out);
            out.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeLong(long i, OutputStream out) {//写long值
        try {
            DataOutputStream dos = new DataOutputStream(out);
            dos.writeLong(i);
        } catch (Exception e) {  e.printStackTrace();    }
    }

    public static long readLong(InputStream in){//根据给定的输入流读取Long值
        try {
            DataInputStream dis = new DataInputStream(in);
            return dis.readLong();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}